package com.woniu.his.dms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.his.cms.client.NonDrugClient;
import com.woniu.his.cms.client.NonDrugItemRecordClient;
import com.woniu.his.cms.client.param.AddNonDrugItemRecordParam;
import com.woniu.his.cms.client.result.DmsNonDrugResult;
import com.woniu.his.cms.client.result.NonDrugItemRecordQuerResult;
import com.woniu.his.dms.common.DmsResultCode;
import com.woniu.his.dms.infra.model.CaseDiseRelation;
import com.woniu.his.dms.infra.model.CaseHistory;
import com.woniu.his.dms.infra.mapper.CaseHistoryMapper;
import com.woniu.his.dms.service.CaseDiseRelationService;
import com.woniu.his.dms.service.CaseHistoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.his.dms.service.DiseService;
import com.woniu.his.dms.service.dto.CaseHistoryDetailDto;
import com.woniu.his.dms.service.dto.CaseHistoryDto;
import com.woniu.his.dms.service.dto.NonDrugDetailDto;
import com.woniu.his.dms.service.param.AddNonDrugItemRecordServiceParam;
import com.woniu.his.dms.service.param.CaseHistorySvcParm;
import com.woniu.his.dms.service.param.DefiniteDiseSVParam;
import com.woniu.his.exception.HisException;
import com.woniu.his.mms.client.HerbalPrescriptionClient;
import com.woniu.his.mms.client.MedicineClient;
import com.woniu.his.mms.client.param.CreateHerbalPrescriptionClientParam;
import com.woniu.his.mms.client.param.CreateMedicineParam;
import com.woniu.his.mms.client.result.HerbalPrescriptionResult;
import com.woniu.his.mms.client.result.MedicineResult;
import com.woniu.his.pms.client.PmsPatientClient;
import com.woniu.his.pms.client.result.StartDiagnosePatientResult;
import com.woniu.his.result.Result;
import com.woniu.his.sms.client.SmsSkdClient;
import com.woniu.his.sms.client.SmsStaffClient;
import com.woniu.his.sms.client.result.LoginStaffResult;
import com.woniu.his.sms.client.result.SkdInfoResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 病历表 服务实现类
 * </p>
 *
 * @author ZJH
 * @since 2022-11-27
 */
@Service
@Slf4j
public class CaseHistoryServiceImpl extends ServiceImpl<CaseHistoryMapper, CaseHistory> implements CaseHistoryService {


    @Resource
    private DiseService diseService;

    @Resource
    private CaseDiseRelationService caseDiseRelationService;

    @Resource
    private PmsPatientClient pmsPatientClient;

    @Resource
    private SmsStaffClient smsStaffClient;

    @Resource
    private SmsSkdClient smsSkdClient;

    @Resource
    private NonDrugItemRecordClient nonDrugItemRecordClient;

    @Resource
    private NonDrugClient nonDrugClient;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private MedicineClient medicineClient;

    @Resource
    private HerbalPrescriptionClient herbalPrescriptionClient;


    //首次提交患者诊断信息,患者做检查或者处置
    @Override
    public CaseHistoryDto submitPriliminaryDise(CaseHistorySvcParm caseHistorySvcParm) {

        //修改为从redis 中获取数据id
        CaseHistory caseHistory;
        //从redis 中获取病历
        String s1 = stringRedisTemplate.opsForValue().get("dms:case:history" + caseHistorySvcParm.getId());
        caseHistory = JSON.parseObject(s1, CaseHistory.class);

        log.info("redis中查到的信息:{}", caseHistory);
        if (caseHistory == null) {
            caseHistory = getById(caseHistorySvcParm.getId());
        }
        if (caseHistory == null) {
            throw new HisException(DmsResultCode.CASE_HISTORY_NOT_EXITS);
        }
        caseHistory = BeanUtil.copyProperties(caseHistorySvcParm, CaseHistory.class);
        //调用患者信息PMS接口，根据患者id，获得患者信息
        Long patientId = caseHistorySvcParm.getPatientId();
        StartDiagnosePatientResult patientResult = pmsPatientClient.queryPatientById(patientId).getData();
        if (patientResult == null) {
            throw new HisException(DmsResultCode.CAN_NOT_FIND_PATIENT);
        }
        caseHistory.setAgeStr(patientResult.getAge());
        caseHistory.setGender(patientResult.getGender());
        caseHistory.setPatientName(patientResult.getName());
        caseHistory.setCreateTime(new Date());
        caseHistory.setCaseHistoryStatus("IN_DOCTOR");
        saveOrUpdate(caseHistory);

        //如果键不存在则新增,存在则不改变已经有的值 再次存入redis中
        String s = "dms:case:history" + caseHistory.getId();
        String text = JSON.toJSONString(caseHistory);

        stringRedisTemplate.opsForValue().setIfAbsent(s, text, 1, TimeUnit.DAYS);
        //输出存入的值
        String s2 = stringRedisTemplate.opsForValue().get("dms:case:history" + caseHistory.getId());
        CaseHistory parse = JSON.parseObject(s2, CaseHistory.class);

        //调用非药品表CMS 生成检查系列 生成处置条码表 non_drug_item_record cmsclient  参数过多 ????
        List<AddNonDrugItemRecordServiceParam> nonDrugItems = caseHistorySvcParm.getNonDrugItems();
        for (AddNonDrugItemRecordServiceParam addNonDrugItemRecordServiceParam : nonDrugItems) {
            AddNonDrugItemRecordParam param = BeanUtil.copyProperties(addNonDrugItemRecordServiceParam, AddNonDrugItemRecordParam.class);
            nonDrugItemRecordClient.addNonDrugItemRecord(param);
        }
        return BeanUtil.copyProperties(caseHistory, CaseHistoryDto.class);
    }


    //确诊疾病,并且安排处方拿药
    @Override
    public void submitDefiniteDise(DefiniteDiseSVParam diseSVParam) {

        CaseHistory caseHistory;
        //从redis 中获取病历
        String s1 = stringRedisTemplate.opsForValue().get("dms:case:history" + diseSVParam.getHistoryId());
        caseHistory = JSON.parseObject(s1, CaseHistory.class);

        log.info("redis中查到的信息:{}", caseHistory);
        if (caseHistory == null) {
            caseHistory = getById(diseSVParam.getHistoryId());
        }
        if (caseHistory == null) {
            throw new HisException(DmsResultCode.CASE_HISTORY_NOT_EXITS);
        }
        //生成疾病病历关联表
        List<Long> diseIds = diseSVParam.getDiseIds();
        diseIds.forEach(o -> {
            if (diseService.getById(o).getStatusDise().equals("OFF")) {
                throw new HisException(DmsResultCode.DISE_CANNOT_USE);
            }
        });
        for (Long diseId : diseIds) {
            CaseDiseRelation caseDiseRelation = new CaseDiseRelation();
            caseDiseRelation.setCaseHistoryId(diseSVParam.getHistoryId());
            caseDiseRelation.setDiseId(diseId);
            caseDiseRelation.setDiseName(diseService.getById(diseId).getNameDise());
            caseDiseRelationService.save(caseDiseRelation);
        }

        //调用MMS,生成拿药处方表和条目表,超过一定时间没拿药,设置状态为诊毕   参数过多??  导入mms接口即可 判断接口是否正常
        CreateHerbalPrescriptionClientParam param = BeanUtil.copyProperties(diseSVParam.getHerbalPreParm(),
                CreateHerbalPrescriptionClientParam.class);
        herbalPrescriptionClient.createHerbalPrescription(param);
        CreateMedicineParam param2 = BeanUtil.copyProperties(diseSVParam.getMedicinePreParm(),
                CreateMedicineParam.class);
        medicineClient.applyMedicine(param2);

        String s = "dms:case:history" + caseHistory.getId();
        String text = JSON.toJSONString(caseHistory);
        stringRedisTemplate.opsForValue().setIfAbsent(s, text, 1, TimeUnit.DAYS);

    }


    //诊毕，设置状态为诊毕
    @Override
    public void endDiagnosis(Long caseHistoryId) {

        CaseHistory caseHistory;
//         从redis 中获取病历
        String s1 = stringRedisTemplate.opsForValue().get("dms:case:history" + caseHistoryId);
        caseHistory = JSON.parseObject(s1, CaseHistory.class);
        log.info("redis中查到的信息:{}", caseHistory);
        if (caseHistory == null) {
            caseHistory = getById(caseHistoryId);
        }
        if (caseHistory == null) {
            throw new HisException(DmsResultCode.CASE_HISTORY_NOT_EXITS);
        }
        caseHistory.setCaseHistoryStatus("OUT_OF_DOCTOR");
        updateById(caseHistory);

        String s = "dms:case:history" + caseHistory.getId();
        String text = JSON.toJSONString(caseHistory);
        stringRedisTemplate.opsForValue().setIfAbsent(s, text, 6, TimeUnit.HOURS);
    }


    //查询历史信息
    @Override
    public CaseHistoryDetailDto selectEndCaseHistoryByReg(Long caseHistoryId) {

        CaseHistory caseHistory;
        //  从redis 中获取病历
//        String s1 = stringRedisTemplate.opsForValue().get("dms:case:history" + caseHistoryId);
//        caseHistory = JSON.parseObject(s1, CaseHistory.class);
//        log.info("redis中查到的信息:{}", caseHistory);
//        if (caseHistory == null) {
            caseHistory = getById(caseHistoryId);
//        }
        if (caseHistory == null) {
            throw new HisException(DmsResultCode.CASE_HISTORY_NOT_EXITS);
        }
        CaseHistoryDetailDto caseHistoryDetailDto = BeanUtil.copyProperties(caseHistory, CaseHistoryDetailDto.class);
        //设置医生姓名  通过医生id获得医生姓名
        LoginStaffResult data = smsStaffClient.findLoginStaffById(caseHistory.getStaffId().intValue()).getData();
        if (data == null) {
            throw new HisException(DmsResultCode.CAN_NOT_FIND_DOCTOR);
        }
        caseHistoryDetailDto.setStaffName(data.getStaffName());
        // 调CMS 通过病例id获得检查信息 CMS
        List<NonDrugItemRecordQuerResult> data1 = nonDrugClient.queryResultByCaseId(caseHistoryId).getData();
        if (data1.size() <= 0) {
            caseHistoryDetailDto.setNonDrugResultDetail(null);
        }
        List<NonDrugDetailDto> list = data1.stream().map(a -> {
            NonDrugDetailDto nonDrugDetailDto1 = new NonDrugDetailDto();
            nonDrugDetailDto1.setId(a.getId());
            for (DmsNonDrugResult datum : nonDrugClient.listAllNonDrug().getData()) {
                if (datum.getId().equals(a.getNoDrugId())) {
                    nonDrugDetailDto1.setNonDrugName(datum.getNonDrugName());
                    break;
                }
            }
            nonDrugDetailDto1.setNonDrugItemStatus(a.getNonDrugItemStatus());
            nonDrugDetailDto1.setCheckResult(a.getCheckResult());
            return nonDrugDetailDto1;
        }).collect(Collectors.toList());
        caseHistoryDetailDto.setNonDrugResultDetail(list);

        // 调MMS 通过病例id获得拿药信息 MMS **
        if (medicineClient.listByReg(caseHistoryId).isSuccess()) {
            List<MedicineResult> data2 = medicineClient.listByReg(caseHistoryId).getData();
            caseHistoryDetailDto.setList(data2);
        }
        if (herbalPrescriptionClient.queryHerbalPrescriptionByCaseId(caseHistoryId).isSuccess()) {
            HerbalPrescriptionResult data3 = herbalPrescriptionClient.queryHerbalPrescriptionByCaseId(caseHistoryId).getData();
            caseHistoryDetailDto.setHerbalPrescriptionResult(data3);
        }
        return caseHistoryDetailDto;
    }


    @Override
    public CaseHistoryDto queryCaseHistoryByRegId(Long RegId) {
        CaseHistory caseHistory = getOne(new QueryWrapper<CaseHistory>().eq("registration_id", RegId));
        return BeanUtil.copyProperties(caseHistory, CaseHistoryDto.class);
    }


    /**
     * @Description: 挂号生成病历
     * @Param:
     * @return:
     * @Date: 2022/11/29
     */
    @Override
    public CaseHistoryDto createCaseHistoryWhenRegistration(Long patientId, Long skdId, Long registrationId) {
        StartDiagnosePatientResult patientResult = pmsPatientClient.queryPatientById(patientId).getData();
        if (patientResult == null) {
            throw new HisException(DmsResultCode.CAN_NOT_FIND_PATIENT);
        }
        List<CaseHistory> list = list(new QueryWrapper<CaseHistory>().eq("patient_id", patientId).
                orderByDesc("create_time"));
        CaseHistory caseHistory = new CaseHistory();
        caseHistory.setPatientId(patientId);
        caseHistory.setCreateTime(new Date());
        caseHistory.setCaseHistoryStatus("REGISTERED");
        caseHistory.setRegistrationId(registrationId);
        caseHistory.setAgeStr(patientResult.getAge());
        caseHistory.setPatientName(patientResult.getName());
        caseHistory.setChiefComplaint("");
        caseHistory.setGender(patientResult.getGender());
        caseHistory.setStartDate(null);
//        SMS 通过排班id 获取医生id  更新sms 依赖即可 **
        SkdInfoResult skdInfoResult = smsSkdClient.findSkdInfoById(skdId).getData();
        if (patientResult.getAge() == null) {
            throw new HisException(DmsResultCode.CAN_NOT_FIND_SKD);
        }
        caseHistory.setStaffId(skdInfoResult.getStaffId());
        //如果在本医院看过病
        if (list.size() > 0) {
            CaseHistory caseHistory1 = list.get(0);
            caseHistory.setHealthCheckup(caseHistory1.getHealthCheckup());
            caseHistory.setHistoryOfPresentIllness(caseHistory1.getHistoryOfPresentIllness());
            caseHistory.setHistoryOfTreatment(caseHistory1.getHistoryOfTreatment());
            caseHistory.setPastHistory(caseHistory1.getPastHistory());
            caseHistory.setAllergies(caseHistory1.getAllergies());
            save(caseHistory);
            String s = "dms:case:history" + caseHistory.getId();
            String text = JSON.toJSONString(caseHistory);
            stringRedisTemplate.opsForValue().setIfAbsent(s, text, 1, TimeUnit.DAYS);
            return BeanUtil.copyProperties(caseHistory, CaseHistoryDto.class);
        }
        //如果未在本医院看过病
        caseHistory.setGender(patientResult.getGender());
        caseHistory.setPatientName(patientResult.getName());
        save(caseHistory);
        //存入redis
        String s = "dms:case:history" + caseHistory.getId();
        String text = JSON.toJSONString(caseHistory);
        stringRedisTemplate.opsForValue().setIfAbsent(s, text, 1, TimeUnit.DAYS);

        return BeanUtil.copyProperties(caseHistory, CaseHistoryDto.class);
    }


}
